<?php

class OrdersController extends Controller
{
	public $layout='//layouts/main';

  public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view', 'create'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	public function actionIndex()
	{
		$order = new Orders;
    $detail = new DetailOrders;

    $count_order = 1;

		$this->render('index', array(
      'order' => $order,
      'detail' => $detail,
      'count_order' => $count_order,
    ));
	}

  public function actionCreate()
  {
    $order = new Orders;
    $detail = new DetailOrders;
    $count_order = 1;

    if(isset($_POST['Orders']))
    {
      $order->attributes = $_POST['Orders'];

      $count_order = (int)$_POST['count_order'];

      $valid = 0;
      if($order->validate())
      {
        $valid = 1;
      }

      for($a=1;$a<=$count_order && $valid == 1;$a++)
      {
        $detail = new DetailOrders;
        $detail->code = $_POST['code'.$a];
        
        if($_POST['quantity'.$a]){
          $detail->quantity = (int)$_POST['quantity'.$a];
        }
        
        $detail->description = $_POST['description'.$a];

        if($detail->validate())
        {
          $order->save();
          $detail->order_id = $order->id;
          $detail->save();

          $valid = 1;
        }
        else
        {
          $valid = 0;
        }        
      }

      if($valid == 1)
      {
        Yii::app()->user->setFlash('success', 'Success');
        Yii::app()->user->setFlash('content', 'Your order has been submitted. Thank you for ordering!');
        
        $this->redirect("index");
      }
    }
    else{
      $count_order = 1;
    }

		$this->render('index', array(
      'order' => $order,
      'detail' => $detail,
      'count_order' => $count_order,
    ));
  }
}
